
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:p_location/common/base/drop_down_view.dart';
import 'package:p_location/common/base/filter_item_click_listener.dart';
import 'package:p_location/common/obj/base_filter_option.dart';
import 'package:p_location/common/obj/page.dart' as MPage;
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/common/widget/common_app_bar.dart';
import 'package:p_location/common/widget/common_button_view.dart';
import 'package:p_location/common/widget/dropdown_menu/gzx/gzx_dropdown_header.dart';
import 'package:p_location/common/widget/dropdown_menu/gzx/gzx_dropdown_menu.dart';
import 'package:p_location/common/widget/dropdown_menu/gzx/gzx_dropdown_menu_controller.dart';
//import 'package:p_location/common/widget/dropdown_menu/dropdown_header.dart';
//import 'package:p_location/common/widget/dropdown_menu/dropdown_menu.dart';
//import 'package:p_location/common/widget/dropdown_menu/dropdown_menu_controller.dart';
import 'package:p_location/common/widget/no_result_widget.dart';
import 'package:p_location/common/widget/search_bar.dart';
import 'package:p_location/net/net_listener.dart';
import 'package:p_location/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

abstract class BaseFilterHeadListView<T> extends StatefulWidget {
  final bool isFromSearch;
  final bool isHiddenAppbar;
  final bool isHiddenBack;

//  final bool hasAdd;

  BaseFilterHeadListViewState getState();

  @override
  BaseFilterHeadListViewState createState() => getState();

  const BaseFilterHeadListView(
      {Key key,
      this.isFromSearch = false,
      this.isHiddenAppbar = false,
      this.isHiddenBack = false})
      : super(key: key);
}

abstract class BaseFilterHeadListViewState<T extends BaseFilterHeadListView>
    extends State<T> implements FilterItemClickListener, NetListener {
  List<String> tabTitles;
  List<List<BaseFilterOption>> filterBundles = [];

  GlobalKey _stackKey = GlobalKey();
  GZXDropdownMenuController _dropdownMenuController = GZXDropdownMenuController();
  List<GZXDropDownHeaderItem> headerTabs = [];
  List<GZXDropdownMenuBuilder> menus = [];

  //以下同base_list_page
  bool isLoading = true;
  String keyWord;

  String errorMsg;
  int currPage = 1;
  int pageNum = 15;
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  List lists = [];

  Map<String, dynamic> params = {};

  @override
  Widget build(BuildContext context) {
    if (widget.isHiddenAppbar) {
      return Scaffold(
        body: _getContentView(),
      );
    } else {
      return Scaffold(
        appBar: widget.isFromSearch
            ? _getSearchAppBar(context)
            : _getCommonAppBar(),
        body: _getContentView(),
      );
    }
  }

  _getCommonAppBar() {
    return CommonAppBar(
      title: Text(
        getTitle(),
        style: TextStyle(color: Colors.black),
      ),
      actions: getActions(),
      onPress: () {
        Navigator.pop(context);
      },
    );
  }

  _getSearchAppBar(context) {
    return SearchBar(
      hideLeft: false,
      hint: '请输入关键字',
      leftButtonClick: _pop,
      rightButtonClick: searchRefresh,
      onChanged: _onKeyWordChanged,
    );
  }

  _pop() {
    Navigator.pop(context);
  }

  void _onKeyWordChanged(String value) {
    keyWord = value;
  }

  void searchRefresh() {
    print('keyword$keyWord');
    _requestList(true);
  }

  _getContentView() {
    if (isLoading) {
      return _getLoadingView();
    }
    if (!StringUtil.isEmpty(errorMsg)) {
      return NoResultWidget('images/img_no_accident.png', errorMsg);
    } else {
      return _getRefreshView();
    }
  }

  _getLoadingView() {
    return Center(
      child: Image.asset('images/timg.gif'),
    );
  }

  _getRefreshView() {
    return Stack(key: _stackKey, children: <Widget>[
      Column(children: <Widget>[
        Offstage(
          offstage: widget.isFromSearch,
          child: GZXDropDownHeader(
            items: headerTabs,
            stackKey: _stackKey,
            controller: _dropdownMenuController,
            height: 40,
            color: Color(0xfff1f1f1),
            dropDownStyle: TextStyle(
              fontSize: 13,
              color: Theme.of(context).primaryColor,
            ),
          ),
        ),
        Expanded(
          child: Container(
            color: Color.fromARGB(255, 239, 239, 243),
            margin: EdgeInsets.only(bottom: hasAdd() ? 60 : 0),
            child: SmartRefresher(
              enablePullDown: false,
              enablePullUp: true,
              header: WaterDropHeader(),
              footer: CustomFooter(
                builder: (BuildContext context, LoadStatus mode) {
                  Widget body;
                  print(mode);
                  if (mode == LoadStatus.idle) {
                    body = Text("上拉加载更多...");
                  } else if (mode == LoadStatus.loading) {
                    body = CircularProgressIndicator();
                  } else if (mode == LoadStatus.failed) {
                    body = Text("加载失败，点击重试...");
                  } else if (mode == LoadStatus.canLoading) {
                    body = Text("上拉加载更多...");
                  } else {
                    body = Text("没有更多数据了...");
                  }
                  return Container(
                    height: 55.0,
                    child: Center(child: body),
                  );
                },
              ),
              controller: _refreshController,
//                  onRefresh: _onRefresh,
              onLoading: _onLoading,
              child: ((!widget.isFromSearch || !StringUtil.isEmpty(keyWord)) &&
                      (lists == null || lists.length == 0))
                  ? NoResultWidget('images/img_no_accident.png', '暂无数据...')
                  : _listView(),
            ),
          ),
        ),
      ]),
      GZXDropDownMenu(
          controller: _dropdownMenuController,
          animationMilliseconds: 300,
          menus: menus),
      CommonButtonView(
        '新增',
        onAddClicked(),
        vanish: !hasAdd(),
      ),
    ]);
  }

  @override
  void initState() {
    super.initState();
    if (!widget.isFromSearch) {
      _requestList(false);
    } else {
      isLoading = false;
    }
    initTabs(getTabTitles());
    initDropMenus();
  }

  _onLoading() {
    currPage++;
    _requestList(false);
  }

  @override
  void deactivate() {
    var bool = ModalRoute.of(context).isCurrent;
    if (needBackRefresh() && bool) {
      _requestList(true);
    }
    super.deactivate();
  }

  @override
  void dispose() {
    _dropdownMenuController.dispose();
    _refreshController.dispose();
    super.dispose();
  }

  _listView() {
    return ListView.builder(
        itemBuilder: (context, index) {
          return createListViewItem(index);
        },
//        separatorBuilder: (context, index) {
//          return Divider(
//            color: Colors.grey,
//            height: 0.4,
//          );
//        },
        itemCount: isInnerFilter() ? outerLength() : lists.length);
  }

  _requestList(bool isRefresh) {
    if (isRefresh) {
      if (!isInnerFilter()) {
        isLoading = true;
        currPage = 1;
        lists.clear();
      }
    }
    if (getSearchKey() != null) {
      params[getSearchKey()] = keyWord ?? '';
    }
    MPage.Page page = MPage.Page(currPage, pageNum);
//    params['page'] = json.decode(page.toJson());
    params['page'] = currPage;
    params['size'] = pageNum;
    params['pageSize'] = pageNum;
    realRequest();
  }

  initTabs(List<String> filterTabs) {
    tabTitles = filterTabs;
    addHeaderItem(tabTitles, true);
  }

  // 该方法执行顺序应该在addHeaderItem 之后
  initDropMenuView(int index, List<BaseFilterOption> options) {
    filterBundles[index] = options;
    DropDownView downView = DropDownView(index, options, this);
    if (index < menus.length) {
      menus[index] = downView.getMenu();
    } else {
      menus.add(downView.getMenu());
    }
  }

  addHeaderItem(List<String> itemTitles, bool isInit) {
    if (itemTitles == null) {
      return;
    }
    headerTabs.clear();
    if (isInit) {
      filterBundles.clear();
    }
    itemTitles.forEach((itemTitle) {
      headerTabs.add(GZXDropDownHeaderItem(itemTitle));
      if (isInit) {
        List<BaseFilterOption> dropMenuFilterOptions = [];
        filterBundles.add(dropMenuFilterOptions);
      }
    });
  }

  @override
  onFilterItemClick(int index, BaseFilterOption filterOption) {
    print(filterOption.getName());
    if (filterOption.getName() == '全部') {
      tabTitles[index] = getTabTitles()[index];
    } else {
      tabTitles[index] = filterOption.getName();
    }
    print(
        'getFilterKeys()[index]${getFilterKeys()[index]}code${filterOption.getCode()}');
//    if (!StringUtil.isEmpty(filterOption.getCode())) {
    params[getFilterKeys()[index]] = filterOption.getCode() ?? '';
//    }
    addHeaderItem(tabTitles, false);
    filterBundles.forEach((o) {
      initDropMenuView(index, filterBundles[index]);
      print('filterBundles[$index]${filterBundles[0].length}');
    });
    _dropdownMenuController.hide();
    setState(() {});
    _requestList(true);
  }

  @override
  void onRequestSuccess(Response response) {
    print('onRequestSuccess');
    setState(() {
      isLoading = false;
      if (response != null && response.data != null) {
        if (currPage == 0) {
          lists.clear();
        }
        lists.addAll(getList(response));
      }
      if (hasNextPage()) {
        _refreshController.loadNoData();
      } else {
        _refreshController.loadComplete();
      }
    });
  }

  @override
  void onRequestError(CommonRes errorRes) {
    print('onRequestError');
    if (errorRes != null) {
      setState(() {
        isLoading = false;
        errorMsg = errorRes.msg;
      });
    }
  }

  // 获取页面标题
  String getTitle();

  List<Widget> getActions();

  List<String> getFilterKeys();

  // 子页面重写
  String getSearchKey() {
    return null;
  }

  // 创建列表项
  createListViewItem(index);

  // 请求
  void realRequest();

  // 请求成功后 转化为相应list
  List getList(response);

  // 分页是否有下一页
  bool hasNextPage();

  bool hasAdd() {
    return false;
  }

  bool isInnerFilter() {
    return false;
  }

  int outerLength() {
    return 0;
  }

  void addEvent() {
    print('addEvent');
  }

  onAddClicked() {
    return () {
      print('点击新增');
      addEvent();
    };
  }

  onRefresh() {
    _requestList(true);
  }

  initDropMenus();

  List<String> getTabTitles();

  bool needBackRefresh() {
    return false;
  }
}
